<script lang="ts">
    import { onMount } from "svelte";
    import type { VirtualListProps, VirtualListStore } from "./VirtualList";
    import VirtualListCore from "./VirtualListCore.svelte";

    let core: any;

    const CONTAINER_CLASSNAME = `cm-virtual-list`;
    let globalContainerStylesheet: HTMLStyleElement = document.querySelector("#cm-virtual-list-styles") as HTMLStyleElement;

    const insertGlobalStylesheet = () => {
        if (!globalContainerStylesheet) {
            globalContainerStylesheet = document.createElement("style");
            globalContainerStylesheet.type = "text/css";

            globalContainerStylesheet.textContent = `
        .${CONTAINER_CLASSNAME} {
            position: relative !important;
            flex-shrink: 0 !important;
            width: 100%;
            height: 100%;
            overflow: auto;
        }
        .${CONTAINER_CLASSNAME} > * {
            width: 100%;
            will-change: transform !important;
            box-sizing: border-box !important;
            contain: layout !important;
        }`;
            document.head.appendChild(globalContainerStylesheet);
        }
    };

    insertGlobalStylesheet();

    const props: VirtualListProps = $props();

    let contentElement: any = $state();
    let bodyElement: any = $state();
    let scrollElement: any = $state();
    const store = $derived<VirtualListStore>({
        scrollElement: scrollElement,
        contentElement: contentElement,
        bodyElement: bodyElement,
    });

    export const getScrollElement = () => {
        return store.scrollElement;
    };
</script>

<div class={CONTAINER_CLASSNAME} bind:this={scrollElement}>
    <div bind:this={contentElement}>
        <div bind:this={bodyElement}>
            <VirtualListCore bind:this={core} {store} {...props} />
        </div>
    </div>
</div>
